    /*
 * Copyright (c) 2022, yifengling0. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. No personal names or organizations' names associated with the
 *    Atomthreads project may be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE ATOMTHREADS PROJECT AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <string.h>
#include "atom.h"
#define ATOM_NONE_STANDARDIO
#include "debug.h"
#include "drv_adc.h"
#include "mraa/aio.h"

#define AIO_PORT 0

static int adc_read(FD fd, char* buffer, size_t maxbytes)
{
    UpboardAdc* adc = (UpboardAdc*)fd;

    mraa_aio_context context = (mraa_aio_context)adc->Protected.context;
    AdcValue* value = (AdcValue*)buffer;

    if (maxbytes == sizeof(AdcValue) && value->channel == AIO_PORT) {
        int result = mraa_aio_read(context);
        value->value = result;
        return OK;
    }

    return NG;
}

static int adc_ioctl(FD fd, int function, void* arg)
{
    return 0;
}


static AdcOps _ops = {
    .refVol = 330,
    .convBits = 1 << 12,
    adc_read,
    adc_ioctl
};


void UpAdcCreate(UpboardAdc *adc, const char* name)
{
    adc->Protected.ops.refVol = 330;
    adc->Protected.ops.convBits = 1 << 12;
    adc->Protected.ops.adc_read = adc_read;
    adc->Protected.ops.adc_ioctl = adc_ioctl;

    mraa_aio_context context =  mraa_aio_init(AIO_PORT);
    adc->Protected.context = (POINTER)context;

    AdcCreate(&adc->Super, name, &_ops);
}
